package com.study.webapp.word;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFStyle;
import org.apache.poi.xwpf.usermodel.XWPFStyles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.study.webapp.controller.BaseController;
import com.study.webapp.po.Word;
import com.study.webapp.service.WordService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/word")
@Api(value = "WordController", description = "word的api")
public class WordController extends BaseController {

	private static String filePath = "D:/wordlib";

	Map<Integer, Long> map = new HashMap<>();

	@Autowired
	private WordService wordService;

	@RequestMapping("/input")
	@ResponseBody
	@ApiOperation(value = "导入word", httpMethod = "POST")
	public String inputWord(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		File tempFile = new File(filePath + File.separator + System.currentTimeMillis() + "-" + fileName);
		try {
			file.transferTo(tempFile);
		} catch (Exception e) {
			System.out.println("格式错误");
		}
		String result = "";
		InputStream in = null;
		try {
			in = new FileInputStream(tempFile);
			initMap();
			String fileType = StringUtils.substringAfterLast(fileName, ".");
			if ("doc".equals(fileType)) {
				result = readDoc(in);
			} else if ("docx".equals(fileType)) {
				result = readDocx(in);
			} else {
				result = "文件格式错误";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return result;
	}

	public String readDocx(InputStream in) {
		Long id = 0L;
		Long cpid = 0L;
		boolean flag = false;
		boolean flagt = false;
		String content = "";
		try {
			XWPFDocument doc = new XWPFDocument(in);
			XWPFStyles style = doc.getStyles();
			Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
			XWPFParagraph para = null;
			while (iterator.hasNext()) {
				para = iterator.next();
				String pstyleId = para.getStyleID();
				if (pstyleId != null) {
					XWPFStyle xstyle = style.getStyle(pstyleId);
					String styleName = xstyle.getName();
					if (!"".equals(content)) {
						Word word = new Word();
						word.setContent(content);
						word.setParentId(cpid);
						word.setStatus(0);
						Long wid = wordService.insertWord(word);
						map.put(5, wid);
						content = "";
					}
					if (styleName.indexOf("1") >= 0) {
						flag = true;
						Word word = new Word();
						word.setTitle(para.getText());
						word.setParentId(0L);
						word.setStatus(0);
						id = wordService.insertWord(word);
						map.put(1, id);
					} else if (styleName.indexOf("2") >= 0) {
						flag = true;
						Word word = new Word();
						word.setTitle(para.getText());
						word.setParentId(map.get(1));
						word.setStatus(0);
						id = wordService.insertWord(word);
						map.put(2, id);
					} else if (styleName.indexOf("3") >= 0) {
						flag = true;
						Word word = new Word();
						word.setTitle(para.getText());
						word.setParentId(map.get(2));
						word.setStatus(0);
						id = wordService.insertWord(word);
						map.put(3, id);
					} else if (styleName.indexOf("4") >= 0) {
						flag = true;
						Word word = new Word();
						word.setTitle(para.getText());
						word.setParentId(map.get(3));
						word.setStatus(0);
						id = wordService.insertWord(word);
						map.put(4, id);
					}
				} else {
					flag = false;
					flagt = true;
					cpid = id;
					content = content + para.getText();
				}
			}
			if (flag == false && flagt == true) {
				Word word = new Word();
				word.setContent(content);
				word.setParentId(cpid);
				word.setStatus(0);
				Long wid = wordService.insertWord(word);
				map.put(5, wid);
				content = "";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "失败";
		}
		return "成功";
	}

	public String readDoc(InputStream in) {
		Long id = 0L;
		Long cpid = 0L;
		boolean flag = false;
		boolean flagt = false;
		String content = "";
		try {
			HWPFDocument doc = new HWPFDocument(in);
			Range r = doc.getRange();
			StyleSheet styleSheet = doc.getStyleSheet();
			int lenParagraph = r.numParagraphs();
			for (int i = 0; i < lenParagraph; i++) {
				Paragraph p = r.getParagraph(i);
				String text = p.text();
				if (text.trim().length() == 0) {
					continue;
				}
				StyleDescription pStyle = styleSheet.getStyleDescription(p.getStyleIndex());
				String styleName = pStyle.getName();
				if (flag == false && flagt == true && styleName.indexOf("正文") < 0) {
					Word word = new Word();
					word.setContent(content);
					word.setParentId(cpid);
					word.setStatus(0);
					Long wid = wordService.insertWord(word);
					map.put(5, wid);
					content = "";
				}
				if (styleName.indexOf("1") >= 0) {
					flag = true;
					Word word = new Word();
					String t = p.text().replaceAll("", "").replaceAll("HYPERLINK ", "<").replaceAll("", "")
							.replaceAll(" ", ">").replaceAll("", "");
					word.setTitle(t);
					word.setParentId(0L);
					word.setStatus(0);
					id = wordService.insertWord(word);
					map.put(1, id);
				} else if (styleName.indexOf("2") >= 0) {
					flag = true;
					Word word = new Word();
					word.setTitle(p.text());
					word.setParentId(map.get(1));
					word.setStatus(0);
					id = wordService.insertWord(word);
					map.put(2, id);
				} else if (styleName.indexOf("3") >= 0) {
					flag = true;
					Word word = new Word();
					word.setTitle(p.text());
					word.setParentId(map.get(2));
					word.setStatus(0);
					id = wordService.insertWord(word);
					map.put(3, id);
				} else if (styleName.indexOf("4") >= 0) {
					flag = true;
					Word word = new Word();
					word.setTitle(p.text());
					word.setParentId(map.get(3));
					word.setStatus(0);
					id = wordService.insertWord(word);
					map.put(4, id);
				} else if (styleName.indexOf("正文") >= 0) {
					flag = false;
					flagt = true;
					cpid = id;
					String t = p.text().replaceAll("HYPERLINK ", "<").replaceAll(" ", ">").replaceAll("", "")
							.replaceAll("", "").replaceAll("", "");
					content = content + t;
				}

			}
			if (flag == false && flagt == true) {
				Word word = new Word();
				word.setContent(content);
				word.setParentId(cpid);
				word.setStatus(0);
				Long wid = wordService.insertWord(word);
				map.put(5, wid);
				content = "";
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "失败";
		}
		return "成功";
	}

	public void initMap() {
		map.put(1, 0L);
		map.put(2, 0L);
		map.put(3, 0L);
		map.put(4, 0L);
		map.put(5, 0L);
	}

}
